package com.seu.project.seuquiz.service.impl;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seu.project.seuquiz.common.ErrorCode;
import com.seu.project.seuquiz.exception.BusinessException;
import com.seu.project.seuquiz.model.dto.userScoreMap.UserScoreMapQueryRequest;
import com.seu.project.seuquiz.model.entity.CollegeContestMap;
import com.seu.project.seuquiz.model.entity.Contest;
import com.seu.project.seuquiz.model.entity.User;
import com.seu.project.seuquiz.model.entity.UserScoreMap;
import com.seu.project.seuquiz.model.req.CollegeContestReq;
import com.seu.project.seuquiz.model.req.CollegeUsersContestParamReq;
import com.seu.project.seuquiz.model.res.CollegeContestRes;
import com.seu.project.seuquiz.model.res.CollegeUsersContestParamRes;
import com.seu.project.seuquiz.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author SoftPro
 * @createDate: 2023-07-16 17:32
 */
@Slf4j
@Service
public class CollegeBizServiceImpl implements CollegeBizService {

    @Resource
    private CollegeContestMapService collegeContestMapService;

    @Resource
    private UserService userService;

    @Resource
    private UserScoreMapService userScoreMapService;

    @Resource
    private ContestService contestService;

    @Override
    public List<CollegeUsersContestParamRes> listCollegeUsersContestByParam(CollegeUsersContestParamReq req) {
        if (req == null) {
            return null;
        }
        String collegeName = req.getCollegeName();
        String major = req.getMajor();
        String studentId = req.getStudentId();
        String studentName = req.getStudentName();
        String contestName = req.getContestName();

        List<CollegeUsersContestParamRes> list = new ArrayList<>();

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.like(StringUtils.isNotBlank(studentId), "studentID", "%" + studentId + "%");
        userQueryWrapper.like(StringUtils.isNotBlank(major), "major", "%" + major + "%");
        userQueryWrapper.like(StringUtils.isNotBlank(collegeName), "college", "%"+collegeName + "%");
        userQueryWrapper.like(StringUtils.isNotBlank(studentName), "userName", "%" + studentName + "%");

        // 查找所有符合条件的学生
        List<User> userList = userService.list(userQueryWrapper);
        if (userList == null || userList.size() <= 0) {
            return new ArrayList<>();
        }

        for (int i = 0; i < userList.size(); i++) {
            User user = userList.get(i);
            CollegeUsersContestParamRes reqResult = new CollegeUsersContestParamRes();
            // 填充用户的学号、学院、专业
            reqResult.setStudentId(user.getStudentID());
            reqResult.setCollegeName(user.getCollege());
            reqResult.setMajor(user.getMajor());
            reqResult.setStudentName(user.getUserName());
            //
            UserScoreMapQueryRequest userScoreMapQueryRequest = new UserScoreMapQueryRequest();
            userScoreMapQueryRequest.setStudentId(user.getStudentID());
            List<UserScoreMap> userScoreList = userScoreMapService.list(userScoreMapService.getQueryWrapper(userScoreMapQueryRequest));
            log.info("学号：{} 的学生参与竞赛情况：{}", user.getStudentID(), userScoreList);
            if (userScoreList == null || userScoreList.size() == 0) {
                continue;
            }

            for (int j = 0; j < userScoreList.size(); j++) {
                CollegeUsersContestParamRes reqRes = new CollegeUsersContestParamRes();
                BeanUtils.copyProperties(reqResult, reqRes);
                // 根据 用户成绩表查询竞赛id
                UserScoreMap userScoreMap = userScoreList.get(j);
                if (userScoreMap == null) {
                    continue;
                }
                String contestId = userScoreMap.getContestId();
                if (StringUtils.isBlank(contestId)) {
                    continue;
                }
                // 填充竞赛得分和时间
                reqRes.setScore(userScoreMap.getScore());
                reqRes.setTime(userScoreMap.getTime());

                // 根据竞赛id查询竞赛名称
                Contest contest = contestService.getById(Long.parseLong(contestId));
                if (contest == null) {
                    continue;
                }

                // 填充竞赛名称 和 竞赛时间
                reqRes.setContestName(contest.getContestName());
                reqRes.setJoinTime(contest.getStartTime());
                list.add(reqRes);
            }

        }
        if (StringUtils.isNotBlank(contestName)) {
            list = list.stream().filter(it -> it.getContestName().contains(contestName)).collect(Collectors.toList());
        }

        return list;
    }

    @Override
    public Page<CollegeUsersContestParamRes> listCollegeUsersContestByParamAndPage(CollegeUsersContestParamReq req, Page page) {
        List<CollegeUsersContestParamRes> list = this.listCollegeUsersContestByParam(req);

        long current = page.getCurrent();    //当前页码
        long size = page.getSize();     // 每页显示条数

        List<CollegeUsersContestParamRes> collect = list.stream().skip((current-1) * size).limit(size).collect(Collectors.toList());
        Page<CollegeUsersContestParamRes> pages = new Page<>(current, size);
        pages.setTotal(list.size());
        pages.setRecords(collect);
        return pages;
    }

    /**
     * 根据学院（可选）、竞赛（可选）  查询记录
     * @param req
     * @return
     */
    @Override
    public List<CollegeContestRes> listCollegeContestRes(CollegeContestReq req) {
        if (req == null) {
            return null;
        }

        String collegeName = req.getCollegeName();
        String contestName = req.getContestName();

        List<String> contestID = null;
        // 如果填写了竞赛先根据竞赛名称查询竞赛id
        if (StringUtils.isNotBlank(contestName)) {
            QueryWrapper<Contest> contestQueryWrapper = new QueryWrapper<>();
            contestQueryWrapper.like("contestName", "%" + contestName + "%");

            List<Contest> contestList = contestService.list(contestQueryWrapper);
            if (contestList == null || contestList.size() <= 0) {
                return new ArrayList<>();
            }

            contestID = contestList.stream().map(Contest::getId)
                    .map(Object::toString)
                    .collect(Collectors.toList());
        }

        // 根据竞赛id和院名查出所有列表
        QueryWrapper<CollegeContestMap> collegeContestMapQueryWrapper = new QueryWrapper<>();
        collegeContestMapQueryWrapper.like(StringUtils.isNotBlank(collegeName), "collegeName", collegeName);
        collegeContestMapQueryWrapper.in(contestID!= null && contestID.size() > 0,"contestID", contestID);
        List<CollegeContestMap> list = collegeContestMapService.list(collegeContestMapQueryWrapper);
        // log.info("符合 学院{}，竞赛名{} 对应竞赛ids{} 的竞赛所有：{}", collegeName, contestName, contestID, JSONUtil.toJsonStr(list));

        if (list == null || list.size() <= 0) {
            return new ArrayList<>();
        }

        // 结果集
        List<CollegeContestRes> collegeContestResList = new ArrayList<>();

        // 遍历符合条件的学院竞赛
        for (CollegeContestMap collegeContestMap : list) {
            String collegeNameRes = collegeContestMap.getCollegeName();
            String contestId = collegeContestMap.getContestId();
            Integer collegeStudentTotal = collegeContestMap.getCollegeStudentTotal();
            Integer joinTotal = collegeContestMap.getJoinTotal();
            Integer totalScore = collegeContestMap.getTotalScore();
            // 根据竞赛id获取竞赛名称
            Contest contestRes = contestService.getById(Integer.parseInt(contestId));
            if (contestRes == null) {
                continue;
            }

            String contestNamRes = contestRes.getContestName();
            Double averageScore = 1.0 * totalScore / joinTotal;
            Double participationRate = 1.0 * joinTotal / collegeStudentTotal;

            // 包装结构
            CollegeContestRes collegeContestRes = new CollegeContestRes();
            collegeContestRes.setCollegeName(collegeNameRes);
            collegeContestRes.setContestName(contestNamRes);
            collegeContestRes.setAverageScore(averageScore);
            collegeContestRes.setParticipationRate(participationRate);

            collegeContestResList.add(collegeContestRes);
        }

        return collegeContestResList;
    }

    @Override
    public Page<CollegeContestRes> listCollegeContestResByPage(CollegeContestReq req, Page page) {
        List<CollegeContestRes> collegeContestResList = this.listCollegeContestRes(req);

        long current = page.getCurrent();    //当前页码
        long size = page.getSize();     // 每页显示条数

        List<CollegeContestRes> collect = collegeContestResList.stream().skip((current-1) * size).limit(size).collect(Collectors.toList());
        Page<CollegeContestRes> pages = new Page<>(current, size);
        pages.setTotal(collegeContestResList.size());
        pages.setRecords(collect);
        return pages;
    }
}
